package com.gulimall.seckill.controller;

import com.common.to.Seckill.SeckillSkuRedisTo;
import com.common.utils.R;
import com.gulimall.seckill.feign.CouponFeignService;
import com.gulimall.seckill.service.impl.SeckillServiceImpl;
import jodd.time.TimeUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @Author Rookie-6688
 * @Description
 * @Create 2021-05-14 10:21
 */
@Slf4j
@Controller
public class SeckillController {

    @Resource
    private SeckillServiceImpl seckillServiceImpl;

    @ResponseBody
    @GetMapping("/getCurrentSeckillSkus")
    public R getCurrentSeckillSkus(){
        log.info("getCurrentSeckillSkus-------------------------");
        List<SeckillSkuRedisTo> seckillSkuRedisToList = seckillServiceImpl.getCurrentSeckillSkus();
        return R.ok().setData(seckillSkuRedisToList);
    }

    /**
     * 根据skuId查询商品是否参加秒杀活动
     */
    @ResponseBody
    @GetMapping(value = "/sku/seckill/{skuId}")
    public R getSkuSeckillInfo(@PathVariable("skuId") Long skuId) {
        try {
            TimeUnit.MICROSECONDS.sleep(300);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        SeckillSkuRedisTo to = seckillServiceImpl.getSkuSeckillInfo(skuId);
        return R.ok().setData(to);
    }

    /**
     * 处理秒杀请求
     * @param killId 场次ID+"-"+skuID
     * @param key 当前商品的秒杀随机码
     * @param num 下单数量
     * @return
     */
    @GetMapping("/kill")
    public String seckill(@RequestParam String killId, @RequestParam String key, @RequestParam Integer num, Model model){
        String orderSn = seckillServiceImpl.seckill(killId, key, num);
        model.addAttribute("orderSn", orderSn);
        return "success";
    }
}
